package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 预定实现类
 *
 * @author zz
 * @since 2022/11/23 10:08
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao ordersettingDao;

    @Override
    public Result submit(Order order) {

        Order oldOrder = orderDao.findOne(order.getMemberId(), order.getOrderDate(),order.getSetmealId());
        Date orderDate = order.getOrderDate();
        Integer reservations = ordersettingDao.findReservations(orderDate);
        Integer number = ordersettingDao.findNumberByOrderDate(orderDate);
        if (oldOrder == null) {
            return this.save(reservations, number, order);
        } else {
            return new Result(false, "不可重复预约");
        }
    }


    public Result save(Integer reservations, Integer number, Order order) {
        Date orderDate = order.getOrderDate();
        if (reservations == null || number == null) {
            return new Result(false, "今日不可预约");
        }
        if (reservations >= number) {
            return new Result(false, "今日预约已满");
        }
        orderDao.save(order);
        reservations+=1;
        ordersettingDao.updateReservations(orderDate,reservations);
        return new Result(true, MessageConst.ORDER_SUCCESS,order);
    }
}
